import CircularCountdown from "./components/CircularCountdown"
import { ButtonRegularOutline } from "@/components/composite/ButtonRegular/main"
import styled from "@emotion/styled"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { css } from "@emotion/react"
import MarginTopBlock from "@/components/base/MarginTopBlock"
import { AnimatePresence, motion } from "motion/react"
import Svg, { SvgComponent } from "@/components/base/Svg"
import { createLogger } from "@/utils/logger"
import { kycForm } from "@/forms"
import { CustomError } from "@/utils/error"
import { computed } from "@preact/signals"
import KycPageSignals from "@/features_signal/kycPageSignals"
import { wait } from "@/utils/common"
import ENV from "@/utils/env"
import { useNavigate } from "react-router-dom"

const logger = createLogger("StepKycOcrCallbackResult")
const ButtonAction = styled(ButtonRegularOutline)`
    margin: 0 24rem;
`

const OcrSuccessIcon = styled(SvgComponent("kyc/ocr_success.svg"))`
    width: 88rem;
    height: 88rem;
`

const OcrFailedIcon = styled(SvgComponent("kyc/ocr_failed.svg"))`
    width: 88rem;
    height: 88rem;
`

export default function StepKycOcrCallbackResult() {
    const form = kycForm.useFormContext()

    // 跳轉回畫面如果 OCR 結果成功，則檢查 OCR 結果是否為 true
    const isOcrCallbackSuccess = !!KycPageSignals.ocrData.value.success
    const [checkOcrResultSuccess, setCheckOcrResultSuccess] = useState<boolean | null>(null)
    const intervalKycAttachmentCheck = useRef<NodeJS.Timeout>(null)
    const [isShowResult, setIsShowResult] = useState(false)
    const navigate = useNavigate()

    const prevPage = useCallback(async () => {
        navigate(location.pathname, { replace: true })
        await wait(300)
        KycPageSignals.prevStage()
    }, [navigate])

    useEffect(() => {
        if (isOcrCallbackSuccess) {
            KycPageSignals.checkOcrResult()
                .then((result) => {
                    setCheckOcrResultSuccess(result)
                    if (result) {
                        intervalKycAttachmentCheck.current = setInterval(async () => {
                            if (checkOcrResultSuccess === null) {
                                await KycPageSignals.fetchKyc()

                                if (KycPageSignals.kycOcrStatus.value === (ENV.dev_mode ? 1 : 2)) {
                                    clearInterval(intervalKycAttachmentCheck.current ?? undefined)
                                    setCheckOcrResultSuccess(true)
                                    navigate(location.pathname, { replace: true })
                                    await wait(100)
                                    KycPageSignals.nextStage()
                                } else {
                                    clearInterval(intervalKycAttachmentCheck.current ?? undefined)
                                    setCheckOcrResultSuccess(false)
                                    logger.info("ocr status", KycPageSignals.kycOcrStatus.value)
                                    setIsShowResult(true)
                                }
                            }
                        }, 1000)
                    }
                })
                .catch((error) => {
                    if (error instanceof CustomError) {
                        form.setError("root", {
                            message: error.message,
                        })
                    } else {
                        form.setError("root", {
                            message: "Failed to check OCR result",
                        })
                    }
                    setIsShowResult(true)
                })
        } else {
            setIsShowResult(true)
        }

        return () => {
            clearInterval(intervalKycAttachmentCheck.current ?? undefined)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isOcrCallbackSuccess])

    const isOcrFinallSuccess = computed(() => {
        if (!isOcrCallbackSuccess) {
            return false
        }

        if (!checkOcrResultSuccess) {
            return false
        }

        return true
    }).value

    const nextStage = useCallback(async () => {
        navigate(location.pathname, { replace: true })
        await wait(50)
        if (isOcrFinallSuccess) {
            KycPageSignals.nextStage()
        } else {
            KycPageSignals.prevStage()
        }
    }, [navigate, isOcrFinallSuccess])

    const actionText = computed(() => {
        return isOcrFinallSuccess ? "Next" : "Retry"
    }).value

    const handleAction = useCallback(async () => {
        nextStage()
    }, [nextStage])

    const FeebackPicture = useMemo(() => {
        return isOcrFinallSuccess ? <OcrSuccessIcon /> : <OcrFailedIcon />
    }, [isOcrFinallSuccess])

    const description = useMemo(() => {
        if (checkOcrResultSuccess === null || !isShowResult) {
            return "ID Verification in progress"
        }
        return isOcrFinallSuccess ? "ID Verification Success" : "ID Verification Failed"
    }, [isOcrFinallSuccess, checkOcrResultSuccess, isShowResult])

    const patienceDescription = useMemo(() => {
        if (checkOcrResultSuccess) {
            return "Your certificate verification will return data in about 10 seconds, please wait patiently"
        }

        return "Your certificate has been authenticated and cannot be authenticated again."
    }, [checkOcrResultSuccess])

    useEffect(() => {
        return () => {
            setCheckOcrResultSuccess(null)
            form.setError("root", {
                message: "",
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    return (
        <div
            css={css`
                flex: 1;
                padding: 0 24rem;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                align-items: stretch;
            `}
        >
            <MarginTopBlock top={32} />
            <AnimatePresence mode="wait">
                <motion.div
                    css={css`
                        height: 200rem;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    `}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.5 }}
                >
                    {!isShowResult ? (
                        <motion.div
                            css={css`
                                width: 104rem;
                                height: 104rem;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                border-radius: 50%;
                            `}
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.5 }}
                        >
                            <CircularCountdown
                                duration={10}
                                onComplete={() => {
                                    clearInterval(intervalKycAttachmentCheck.current ?? undefined)
                                    setIsShowResult(true)
                                }}
                                strokeWidth={6}
                            />
                        </motion.div>
                    ) : (
                        <motion.div
                            css={css`
                                width: 104rem;
                                height: 104rem;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                background-color: ${isOcrFinallSuccess ? "#cdffc5" : "#ffd8d8"};
                                border-radius: 50%;
                            `}
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.5 }}
                        >
                            {FeebackPicture}
                        </motion.div>
                    )}
                </motion.div>
            </AnimatePresence>
            <MarginTopBlock top={12} />
            <div
                css={css`
                    font-family: Gilroy;
                    font-weight: 700;
                    font-size: 20rem;
                    line-height: 32rem;
                    letter-spacing: 0%;
                    text-align: center;
                    text-transform: capitalize;
                    color: #000000;
                `}
            >
                {description}
            </div>
            <MarginTopBlock top={16} />
            <div
                css={css`
                    font-family: Gilroy;
                    font-weight: 500;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    text-align: center;
                `}
            >
                {patienceDescription}
            </div>
            <div
                css={css`
                    flex: 1;
                `}
            />
            {isShowResult && <ButtonAction onClick={handleAction}>{actionText}</ButtonAction>}
        </div>
    )
}
